package cc.vv.party.service.impl;

import cc.vv.party.beans.model.PolicyDoc;
import cc.vv.party.beans.vo.PolicyDocVO
import cc.vv.party.mapper.PolicyDocMapper;
import cc.vv.party.service.PolicyDocService;
import cc.vv.party.common.base.BaseServiceImpl;
import cc.vv.party.common.constants.StatusCode
import cc.vv.party.common.ext.wrapper
import cc.vv.party.common.wrapper.PageWrapper
import cc.vv.party.exception.BizException
import cc.vv.party.param.PolicyDocEditParam
import cn.hutool.core.date.DatePattern
import cn.hutool.core.date.DateUtil
import com.baomidou.mybatisplus.mapper.EntityWrapper
import com.baomidou.mybatisplus.plugins.Page
import commonx.core.content.transfer
import org.apache.commons.lang.StringUtils
import org.springframework.stereotype.Service;
import java.util.*

/**
 * <p>
 * 政策文件信息 服务实现类
 * </p>
 *
 * @author Gyb
 * @since 2018-10-12
 */
@Service
open class PolicyDocServiceImpl : BaseServiceImpl<PolicyDocMapper, PolicyDoc>(), PolicyDocService {


    override fun edit(param: PolicyDocEditParam, userId: String): Boolean {
        if(StringUtils.isBlank(param.id)){
            var entity = param.transfer<PolicyDoc>()
            entity.createUser = userId
            return super.insert(entity)
        } else {
            var entity = super.selectById(param.id) ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST)
            if(StringUtils.isNotBlank(param.title)) entity.title = param.title
            if(StringUtils.isNotBlank(param.source)) entity.source = param.source
            if(param.releaseTime != null) entity.releaseTime = Date(param.releaseTime!!)
            if(StringUtils.isNotBlank(param.releaseContent)) entity.releaseContent = param.releaseContent
            return super.updateById(entity)
        }
    }

    override fun info(id: String): PolicyDocVO {
        var entity = super.selectById(id) ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST)
        return entity.transfer()
    }

    override fun listPage(title: String?, releaseTime: Long?, size: Int, page: Int): PageWrapper<PolicyDocVO> {
        var wrapper = EntityWrapper<PolicyDoc>()
        if(StringUtils.isNotBlank(title)) wrapper.like("title", title)
        if(releaseTime != null) wrapper.and("DATE_FORMAT(release_time, '%Y-%m-%d') = {0}", DateUtil.format(Date(releaseTime), DatePattern.NORM_DATE_PATTERN))
        wrapper.orderBy("create_time", false)
        var pages = super.selectPage(Page(page, size), wrapper)
        return pages.wrapper()
    }

}
